<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

    protected $user_info;
    protected $user;
    public function  __construct()
    {
        parent::__construct();
//        $this->user = new UserModel();
//        if(!getSysStatus()){
//            header("Content-type:text/html;charset=utf-8");
//            exit('系统维护中....');
//        }

        $this->user_info =  session('User_yctr');
        $info=session('User_yctr');
        if($info['status']==2){
            session('User_yctr',null);
            $this->redirect('Public/login');
        }
//        if(!$this->user_info){
//
//            $this->redirect('Index/index');
//        }

    }

    public function index(){

//       $userList= M('user')->select();
//        foreach ($userList as $key=>$v){
//            $uid= $this->randNumber1(8);
//            M('user')->where(['id'=>$v['id']])->save(['uid'=>$uid]);
//
//        }
//        echo 'success';die;
        if(!session('User_yctr')){
        $this->redirect('Public/login');
//            $this->redirect('User/index');
        }

        //VIP申请
        $user_id=$this->user_info['id'];
        $agent1=M('agent')->where(['uid'=>$user_id,'status'=>['in',[1,2]]])->find();
        if($agent1){
            $status=1;
        }else{
            $status=0;
        }
        $this->assign('status',$status);
        //商学院内容
        $notice = M('news')->where(array('type'=>5,'language'=>2,'status'=>1,'type'=>1))->order('create_time desc')->find();
        $this->assign('notice',$notice);

        $config=M('reward_config')->find();
        $this->assign('user_id',session('User_yctr'));
        $lunbo=M('lunbo')->select();
        $this->assign('lunbo',$lunbo);
        $this->assign('config',$config);
        $this->display();
    }

    /**
     * 升级专区产品
     */
    public function uplevel(){
        //获取前三个首页推荐产品
        $where['a.status'] = 1;//上架
        $join = 'left join '.C('DB_PREFIX').'goods_img as g on a.id = g.goods_id';
        $groomGoods = M('goods')->where($where)
            ->alias('a')
            ->join($join)
            ->order('sort desc')
            ->limit(3)
            ->field('a.*,g.path')
            ->select();

        $this->assign('groomGoods',$groomGoods);
        $this->assign('goodsList',$this->getGoodsList());
        $this->assign('goodsList2',$this->getGoodsList2());
        $this->assign('g_class',$this->getClass());
        $this->assign('lunbo',$this->getLunBo());
        $this->assign('news',$this->getNews());
        $config = M('reward_config')->find(1);
        $this->assign('commission',$config['duipeng_2']);
        $this->display();
    }

    //轮播图
    private function getLunBo()
    {
        return M('lunbo')->select();
    }

    public function news()
    {

        $this->assign('data',M('news')->where()->select());
        $this->display();
    }


    public function newsdetail()
    {
        $id = I('get.id',0);
        if($id){
            $this->assign('data',M('news')->find($id));
        }
        $this->display();
    }

    public function choujiang()
    {
        //配置文件
        $config=M('reward_config')->find(1);
        $userinfo=session('User_yctr');
        $userid=$userinfo['id'];
        $res=M('lottery')->where(array('status'=>1))->order('lottery_id desc')->select();
        if($res){
            $status=1;
        }else{
            $status=0;
        }
        foreach ($res as $k=>$v){
            $res[$k]['already_user']=M('lottery_user')->where(array('lottery_id'=>$v['lottery_id'],'uid'=>$userid))->sum('number');
            $count=M('lottery_user')->where(array('lottery_id'=>$v['lottery_id']))->count("distinct(uid)");
            $res[$k]['count']=$count;

            $res[$k]['least_exuu']=round($v['least_tou']/$config['ptr17'],2);//起投的exuu
        }
        //往期中奖结果
        $winner=M('lottery_winner')->where('status=0')->order('lottery_id desc')->select();
        $record=array();
        foreach ($winner as $k=>$v){
            $record[$k]['lottery_id']=$v['lottery_id'];
            $winner_user=M('user')->where(array('id'=>$v['uid']))->find();
            $record[$k]['eth_address']=$winner_user['eth_address'];
            $record[$k]['username']=$winner_user['username'];
            $record[$k]['award']=$v['award'];
        }
        $this->assign('record',$record);
//        dump($res);die;

//        $count1=M('lottery_user')->where(array('lottery_id'=>9))->group('uid')->count();
//        dump($count1);die;


        $news=M('lottery_winner')->alias('lw')->join('ms_lottery l on l.lottery_id=lw.lottery_id')->where('lw.status=0')->order('l.lottery_time desc')->limit(3)->select();
        foreach ($news as $k=>$v){
            $news[$k]['username']=M('user')->where(array('id'=>$news[$k]['uid']))->getField('username');
        }
        $this->assign('news',$news);

        $user=M('user')->where(array('id'=>$userid))->find();
        $this->assign('exuu',$user['z1']);
        $this->assign('usdt',$user['z8']);
        $this->assign('status',$status);
        $this->assign('data',$res);
        $this->display();
    }

    //抽奖确认
    public function onecoin(){
        $data=I("post.");
//        dump($data);die;
        $userinfo=session('User_yctr');
        $id=$userinfo['id'];//用户id
        $user=M('user')->where(array('id'=>$id))->find();//用户数据
        $password2=M('user')->where(array('id'=>$id))->getField('password2');

        if ($data['coin']==1){//投币exuu
            if ($data['amount']>$user['z1']){
                ajax_return(0,'您的余额不足');
            }
        }elseif ($data['coin']==8){//投币usdt
            if ($data['amount']>$user['z8']){
                ajax_return(0,'您的余额不足');
            }
        }
        if(md5($data['password2'])!=$password2){
            ajax_return(0,'密码错误');
        }
        $user_all=M('lottery_user')->where(array('lottery_id'=>$data['lottery_id'],'uid'=>$id))->sum('number');//用户已投入的数量
        $award_price=M('lottery')->where(array('id'=>$data['id']))->getField('award_price');//奖品价值
        if($user_all+1>$award_price){//判断投入的数量不得超过奖品价值
            ajax_return(0,'投入的注数超过奖品价值，不可再投了！');
        }
        M()->startTrans();
        $lottery_user['uid']=$id;
        $lottery_user['lottery_id']=$data['lottery_id'];
        $lottery_user['coin']=$data['coin'];//投币的币种
        $lottery_user['amount']=$data['amount'];//投币的数量
        $lottery_user['number']=1;
        $lottery_user['user_address']=$userinfo['eth_address'];
        $lottery_user['time']=time();
        $res1=M('lottery_user')->add($lottery_user);//用户参与 抽奖的记录
        $res2=M('lottery')->where(array('id'=>$data['id']))->setInc('already_biao');//已投标数加1
        $res3=M('user')->where(array('id'=>$id))->setDec('z'.$data['coin'],$data['amount']);//用户usdt/exuu数减1
        if($res1&&$res2&&$res3){//事务
            M()->commit();
            $this->add_fmoney($id,$id,$data['amount'],$data['coin'],$data['coin'].'13','参与抽奖');
            //查看这期已投标数与满标是否相等
            $lottery=M('lottery')->where(array('id'=>$data['id']))->find();
            if($lottery['already_biao']==$lottery['mark_number']){
                //满标开奖
                $tomorrow=strtotime(date('Y-m-d',strtotime('+1 day')))+10*60*60;//第二天11点开奖；时间戳

                //修改抽奖状态
//                $res4=M('lottery')->where(array('id'=>$data['id']))->save(array('status'=>0));//抽奖 表状态改为0（结束）
                $res4=M('lottery')->where(array('id'=>$data['id']))->save(array('flag'=>2,'lottery_time'=>$tomorrow));//抽奖 表状态改为2（待开奖）

                //查看是否指定中奖

                if($lottery_fixed=M('lottery_fixed')->where(array('lottery_id'=>$lottery['lottery_id']))->find()){
//                    dump($lottery_fixed);die;
                    $winner=$lottery_fixed['uid'];
                }else{
                    $user_arr=M('lottery_user')->where(array('lottery_id'=>$data['lottery_id']))->getField('uid',true);
//                    dump($user_arr);die;
                    $winner=$user_arr[array_rand($user_arr)];//随机取一个uid用户
                }

                $lottery_winner['uid']=$winner;
                $lottery_winner['lottery_id']=$data['lottery_id'];
                $lottery_winner['award_price']=$lottery['award_price'];
                $lottery_winner['award']=$lottery['award'];
                $lottery_winner['status']=1;//已生成winner但不显示
//                $lottery_winner['lottery_time']=$tomorrow;
                $lottery_winner['number']=M('lottery_user')->where(array('lottery_id'=>$data['lottery_id'],'uid'=>$winner))->sum('number');//中奖者已投多少标
                M('lottery_winner')->add($lottery_winner);//更新中奖者表
//                M('lottery')->where(array('id'=>$data['id']))->save(array('lottery_time'=>time()));
//                $this->add_fmoney(1,1,1,8,810,'系统自动开奖');
//                $news['title']='第'.$data['lottery_id'].'期抽奖';
//                $news['content']='恭喜获得'.$lottery['award'].'奖品';
//                $news['type']=2;//1为平台公告2为系统公告
//                $news['create_time']=time();
//                M('news')->add($news);//中奖者发布消息
                ajax_return('1','投注成功，达到满标，明天10点开奖');
            }
            ajax_return(1,'投注成功');
        }else{
            M()->rollback();
            ajax_return(0,'投注失败');
        }


        dump($data);die;
    }

    //自动第二天开奖
    public function auto_lottery(){
//        $map['status']=0;
//        $map['flag']=2;
//        $map['lottery_time']=array('elt',time());
        $where['lottery_time']=array(array('egt',strtotime(date('Y-m-d'))),array('elt',strtotime(date('Y-m-d'))+86399));
//        $where['lottery_time']=array('egt',strtotime(date('Y-m-d')));
//        $where['lottery_time']=array('elt',strtotime(date('Y-m-d'))+86399);
        $lottery=M('lottery')->where($where)->select();//今天开奖的期
        $data=[];
//        dump($where);
        if ($lottery){
            foreach ($lottery as $k=>$v){
                if (time() >= $v['lottery_time']){
                    //开奖
//                    if ($v['status']==1 && $v['flag']==2){//开奖改变状态值
//                        M('lottery')->where(array('id'=>$v['id']))->save(array('status'=>0,'flag'=>1));
//                    }
                    //传递该条期数
                    $uid=M('lottery_winner')->where(array('lottery_id'=>$v['lottery_id']))->getField('uid');
                    $data[$k]['username']=M('user')->where(array('id'=>$uid))->getField('username');
                    $data[$k]['lottery_id']=$v['lottery_id'];
                }
            }
        }

        ajax_return(1,'',$data);

    }

    //自动第二天开奖
    public function auto_lottery_bak(){
        $map['status']=0;
        $map['flag']=1;
        $map['lottery_time']=array('egt',strtotime(date('Y-m-d')));
        $lottery=M('lottery')->where($map)->select();
        $data=[];
        if($lottery){
            foreach ($lottery as $k=>$v){

                    $uid=M('lottery_winner')->where(array('lottery_id'=>$v['lottery_id']))->getField('uid');
                    $data[$k]['username']=M('user')->where(array('id'=>$uid))->getField('username');
                    $data[$k]['lottery_id']=$v['lottery_id'];

            }
        }

        ajax_return(1,'',$data);

    }


    public function sort()
    {
        $this->assign('data',$this->getClass());
        $this->display();
    }
    //商城公告模块
    public function getNews()
    {

        $map['status'] = 1;
        return M('news')->where($map)->order('create_time desc')->limit(7)->field('id,title')->select();
    }


    public function  add_fmoney($user_id,$from_id,$amount,$type,$reward_type,$tips)
    {
        $map['user_id'] =$user_id;
        $map['from_id'] = $from_id;
        $map['amount'] = $amount;
        $map['type'] = $type;
        $map['reward_type'] = $reward_type;
        $map['tips'] = $tips;
        $map['create_time'] = time();
        return M('fmoney')->add($map);
    }

    private function getClass()
    {
        $w['status'] = 1;
        $b = M('belong')->where($w)->select();
        $gc = M('goods_class');
        foreach ($b as  $k=>$v){
            $map['belong'] = $v['id'];
            $children = $gc->where($map)->select();
            $arr[$k]['b_name'] =$v['name'];
            $arr[$k]['children'] =$children;
        }



        return $arr;
    }


    public function selectpay(){
        header('Content-Type: text/html; charset=UTF-8');
        $order_num = I('id');
        $order = M('recharge')->where('order_num = "'.$order_num.'"')->find();
        if(!$order){
            $this->error('非法参数');
        }
        Vendor('WxPayv3.JSAPI');  
        $tools = new \JsApiPay();
        $openid = $tools->GetOpenid();
        $total_money = $order['amount'];

        $input = new \WxPayUnifiedOrder();
        $input->SetBody("余额充值");//商品或支付单简要描述
        $input->SetAttach($order['order_num']); //附加数据
        $input->SetOut_trade_no($order['order_num']);//传的值
        $input->SetTotal_fee($total_money*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("余额充值");
        $url = 'http://'.$_SERVER['SERVER_NAME'].'/index.php/index/notifydfc';
        $input->SetNotify_url($url);
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);


        $or = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($or);

        $this->assign('jsApiParameters',$jsApiParameters);
        $this->assign("total_money",$total_money);
        $this->assign('order',$order);
        $this->display();
    }


    public function notifydfc()
    {
        Vendor('WxPayv3.JSAPI');  
        $xmlObj = simplexml_load_string($GLOBALS['HTTP_RAW_POST_DATA']); //解析回调数据
        $out_trade_no = $xmlObj->out_trade_no;//订单号
        $total_fee = $xmlObj->total_fee;//支付价格
        $openid = $xmlObj->openid;//
        $queryorder = new \MicroPay();
        $rejg = $queryorder->query($out_trade_no);

        if ($rejg) {
            $order = M('recharge')->where('order_num = "' . $out_trade_no . '"')->find();
            if ($order['status'] == 2) {
                file_put_contents("no.txt", $out_trade_no.'订单已经支付');
                $this->redirect('User/index');
                exit();
            } else {
                //$sub_where['sum_id'] = $order['id'];
                $sum['status'] = '2';
                //  $sum['payment'] = '1';//在线支付
                M('recharge')->where('id = "' . $order['id'] . '"')->save($sum);
                $user = M('user')->find($order['user_id']);
                $save['id'] = $order['user_id'];
                $save['pocket']  = $user['pocket']+$order['amount'];
                //$save['status']  = 2;
                M('user')->save($save);

                $map['user_id'] = $user['id'];
                $map['amount'] = $order['amount'];
                $map['type'] = 1;
                $map['create_time'] = time();
                $map['tips'] = '账户充值';
                // $map['account'] = $account;
                $map['flag'] = '+';
                M('money_detail')->add($map);

//                $db = M();
//                $a = $order['user_id'];
//                $where['level'] = $order['level'];
//
//                $c = M('config')->where($where)->count();
//                $b = $order['level'];
//                $aa = $db->execute("call jiangjin($a,$c,$b)");//正常


                // $m1 = '0.91';
                // $m2 = '0.92';
                // $m3 = '0.93';

                // $this->redirect('User/index');

            }
        }
    }

}